package com.jagochan.imchat.module.user.adaptor;

import cn.hutool.core.bean.BeanUtil;
import com.jagochan.imchat.module.user.domain.entity.ItemConfig;
import com.jagochan.imchat.module.user.domain.entity.User;
import com.jagochan.imchat.module.user.domain.entity.UserBackpack;
import com.jagochan.imchat.module.user.domain.resp.BadgeResp;
import com.jagochan.imchat.module.user.domain.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;

import java.util.*;
import java.util.stream.Collectors;

public class UserAdaptor {

    public static User buildRegister(String openId) {
        User user = new User();
        user.setOpenId(openId);
        return user;
    }

    public static User buildAuthorize(Long uid, WxOAuth2UserInfo userInfo) {
        User user = new User();
        user.setId(uid);
        user.setOpenId(user.getOpenId());
        user.setName(userInfo.getNickname());
        user.setAvatar(userInfo.getHeadImgUrl());
        return user;
    }

    public static UserInfoResp buildUserInfoResp(User user, Integer modifyNameCount) {
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtil.copyProperties(user, userInfoResp);
        userInfoResp.setModifyNameCount(modifyNameCount);
        return userInfoResp;
    }

    public static List<BadgeResp> buildBadgeRespList(List<ItemConfig> badgeList, List<UserBackpack> backpackList, User user) {
        // 拿到当前用户拥有的徽章ID
        Set<Long> obtainItemIds = backpackList.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());

        return badgeList.stream().map(itemConfig -> {
            BadgeResp badgeResp = BeanUtil.copyProperties(itemConfig, BadgeResp.class);
            badgeResp.setObtain(obtainItemIds.contains(itemConfig.getId()) ? 1 : 0); // 是否拥有（0否1是）
            badgeResp.setWearing(Objects.equals(user.getItemId(), itemConfig.getId()) ? 1 : 0); // 是否佩戴（0否1是）
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing, Comparator.reverseOrder()) // 佩戴的优先排在前面
                .thenComparing(BadgeResp::getObtain, Comparator.reverseOrder()) // 拥有的优先排在前面
        ).collect(Collectors.toList());
    }
}
